package com.ssy.lingxi.platform.manage.serviceimpl.content;

import cn.hutool.core.util.StrUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.api.model.dto.material.MaterialFileInfoDTO;
import com.ssy.lingxi.platform.manage.api.model.vo.material.MaterialFileFeignVO;
import com.ssy.lingxi.platform.manage.entity.content.MaterialLibrary;
import com.ssy.lingxi.platform.manage.entity.content.QMaterialLibrary;
import com.ssy.lingxi.platform.manage.model.request.content.MaterialLibraryAddRequest;
import com.ssy.lingxi.platform.manage.model.request.content.MaterialLibraryBatchDelRequest;
import com.ssy.lingxi.platform.manage.model.request.content.MaterialLibraryDelRequest;
import com.ssy.lingxi.platform.manage.model.request.content.MaterialLibraryPageRequest;
import com.ssy.lingxi.platform.manage.repository.MaterialLibraryRepository;
import com.ssy.lingxi.platform.manage.service.content.IMaterialLibraryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 素材库管理 - 业务实现层
 *
 * @author xiechenhui
 * @version 2.0.0
 * @date 202224/03/24
 */
@Service
public class MaterialLibraryServiceImpl implements IMaterialLibraryService {

    @Resource
    private MaterialLibraryRepository materialLibraryRepository;

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 素材管理分页查询
     * @param request   参数
     * @param user      登录信息
     * @return
     */
    @Override
    public Wrapper<PageData<MaterialLibrary>> page(MaterialLibraryPageRequest request, UserLoginCacheDTO user) {
        //表实体
        QMaterialLibrary qMaterialLibrary = QMaterialLibrary.materialLibrary;
        //构造查询条件
        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(qMaterialLibrary.memberId.eq(user.getMemberId()));
        predicates.and(qMaterialLibrary.memberRoleId.eq(user.getMemberRoleId()));

        if (StrUtil.isNotBlank(request.getFileName())) {
            predicates.and(qMaterialLibrary.fileName.like("%" + request.getFileName() + "%"));
        }
        if (Objects.nonNull(request.getFileType())) {
            predicates.and(qMaterialLibrary.fileType.eq(request.getFileType()));
        }
        if (Objects.nonNull(request.getStartTime())) {
            predicates.and(qMaterialLibrary.uploadTime.goe(LocalDateTime.parse(request.getStartTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        }
        if (Objects.nonNull(request.getEndTime())) {
            predicates.and(qMaterialLibrary.uploadTime.loe(LocalDateTime.parse(request.getEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
        }

        JPAQuery<MaterialLibrary> query = jpaQueryFactory.select(qMaterialLibrary).from(qMaterialLibrary).where(predicates);
        long totalCount = query.fetchCount();
        List<MaterialLibrary> list = query.orderBy(qMaterialLibrary.id.desc()).offset(request.getCurrentOffset()).limit(request.getPageSize()).fetch();
        return Wrapper.success(new PageData<>(totalCount, list));
    }

    /**
     * 新增素材
     * @param request   参数
     * @param sysUser   登录信息
     * @return
     */
    @Override
    public Wrapper<Void> add(MaterialLibraryAddRequest request, UserLoginCacheDTO sysUser) {
        MaterialLibrary material = materialLibraryRepository.findFirstByFileNameAndMemberIdAndMemberRoleId(request.getFileName(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if(Objects.nonNull(material)){
            return Wrapper.fail(ResponseCode.LS_DATA_NO_REPEAT);
        }
        MaterialLibrary materialLibrary = new MaterialLibrary();
        materialLibrary.setFileName(request.getFileName());
        materialLibrary.setFileUrl(request.getFileUrl());
        materialLibrary.setFileType(request.getFileType());
        materialLibrary.setUploadTime(LocalDateTime.now());
        materialLibrary.setMemberId(sysUser.getMemberId());
        materialLibrary.setMemberRoleId(sysUser.getMemberRoleId());
        materialLibrary.setMemberRoleName(sysUser.getMemberRoleName());
        materialLibraryRepository.saveAndFlush(materialLibrary);
        return Wrapper.success();
    }

    /**
     * 删除素材
     * @param request   参数
     * @param sysUser   登录信息
     * @return
     */
    @Override
    public Wrapper<Void> del(MaterialLibraryDelRequest request, UserLoginCacheDTO sysUser) {
        Long id = request.getId();
        MaterialLibrary materialLibrary = materialLibraryRepository.findById(id).orElse(null);
        if(Objects.isNull(materialLibrary)){
            return Wrapper.fail(ResponseCode.SYSTEM_RECORDS_DON_T_EXIST);
        }
        materialLibraryRepository.delete(materialLibrary);
        return Wrapper.success();
    }

    /**
     * 批量删除素材
     * @param request   参数
     * @param sysUser   登录信息
     * @return
     */
    @Override
    public Wrapper<Void> batchDel(MaterialLibraryBatchDelRequest request, UserLoginCacheDTO sysUser) {
        //id集合
        List<Long> idList = request.getIdList();
        if(CollectionUtils.isEmpty(idList)){
            return Wrapper.fail(ResponseCode.REQUEST_LIST_PARAM_CHECK_FAILED);
        }
        List<MaterialLibrary> materialLibraryList = materialLibraryRepository.findByIdInAndMemberIdAndMemberRoleId(idList, sysUser.getMemberId(), sysUser.getMemberRoleId());
        if(CollectionUtils.isEmpty(materialLibraryList)){
            return Wrapper.fail(ResponseCode.SYSTEM_RECORDS_DON_T_EXIST);
        }
        //批量删除
        materialLibraryRepository.deleteAll(materialLibraryList);
        return Wrapper.success();
    }

    /**
     * 根据会员id和角色id查询素材库细腻
     * @param request   参数
     * @return
     */
    @Override
    public Wrapper<List<MaterialFileFeignVO>> findAllByMemberIdAndRoleId(MaterialFileInfoDTO request) {
        List<MaterialLibrary> materialLibraryList = materialLibraryRepository.findByMemberIdAndMemberRoleId(request.getMemberId(), request.getMemberRoleId());
        List<MaterialFileFeignVO> materialFileFeignVOList = materialLibraryList.stream().map(materialLibrary -> {
            MaterialFileFeignVO materialFileFeignVO = new MaterialFileFeignVO();
            materialFileFeignVO.setFileName(materialLibrary.getFileName());
            materialFileFeignVO.setUrl(materialLibrary.getFileUrl());
            return materialFileFeignVO;
        }).collect(Collectors.toList());
        return Wrapper.success(materialFileFeignVOList);
    }
}
